package com.skyworth.web;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.After;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by cody on 2016/8/8.
 *
 * 单元测试基类
 *
 *
 */
public class JUnitTestBase {

    protected Logger Log ;

    protected Gson gson;

    private String xmlPath;
    private ClassPathXmlApplicationContext mContext;
    public JUnitTestBase(){
        this.xmlPath = "classpath:spring-autoscan.xml";
    }

    public JUnitTestBase(String xmlPath){
        this.xmlPath = xmlPath;
    }

    @Before
    public void before(){
        Log = LoggerFactory.getLogger(JUnitTestBase.class);
        gson = new GsonBuilder().setPrettyPrinting().create();
        if(xmlPath == null){
            xmlPath = "classpath*:spring-*.xml";
        }

        try{
            mContext = new ClassPathXmlApplicationContext(xmlPath.split(("[,\\s]+")));
            mContext.start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @After
    public void after(){
        mContext.destroy();
    }

    protected <T> T getBean(String id){
        return (T) mContext.getBean(id);
    }

    protected <T> T getBean(Class<T> clazz){
        return mContext.getBean(clazz);
    }


    protected void println(String msg){
        System.out.println("cody  " + this.getClass().getSimpleName() + "    " + msg);
    }

    protected void println(Object object){
        System.out.println("cody  " + this.getClass().getSimpleName() + "    " + gson.toJson(object));
    }

}
